from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication
from rest_framework_jwt.utils import jwt_decode_handler
from rest_framework.exceptions import AuthenticationFailed
import jwt

#自定义基于jwt的认证类
class LoginAuthentication(BaseJSONWebTokenAuthentication):
    def authenticate(self, request):
        jwt_value = request.META.get('HTTP_AUTHORIZATION')
        print(jwt_value)
        if jwt_value:
            try:
                payload = jwt_decode_handler(jwt_value)
                print(payload)
            except jwt.ExpiredSignature:
                raise AuthenticationFailed('签名过期')
            except jwt.InvalidTokenError:
                raise AuthenticationFailed('用户非法')
            except Exception as e:
                raise AuthenticationFailed(str(e))
            user = self.authenticate_credentials(payload)
            return user, jwt_value
        else:
            raise AuthenticationFailed('未登录，请先登录')
